<template>
  <div class="page-content">
    <div class="header">
      <h3>设备系统管理</h3>
    </div>

    <div class="filter-bar">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索系统版本..."
            clearable
            @clear="fetchAndroidVersions(1)"
            @keyup.enter="fetchAndroidVersions(1)"
          >
            <template #append>
              <el-button @click="fetchAndroidVersions(1)">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="12" class="action-buttons">
          <el-button 
            type="danger" 
            :disabled="selectedVersions.length === 0"
            @click="batchDeleteVersions"
            v-ripple
          >
            批量删除
          </el-button>
        </el-col>
      </el-row>
    </div>

    <el-table
      v-loading="loading"
      :data="androidVersions"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="android_name" label="系统版本名称" />
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column prop="updated_at" label="更新时间" width="180" />
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <el-button 
            type="danger" 
            size="small" 
            @click="deleteVersion(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAndroidVersionList, 
  deleteAndroidVersion,
  batchDeleteAndroidVersions
} from '@/Newapi/device'

// 接口类型定义
interface AndroidVersion {
  id: number
  created_at: string
  updated_at: string
  android_name: string
}

// 状态变量
const loading = ref(false)
const androidVersions = ref<AndroidVersion[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const selectedVersions = ref<AndroidVersion[]>([])

// 初始化
onMounted(() => {
  fetchAndroidVersions(1)
})

// 获取系统版本列表
const fetchAndroidVersions = async (page: number) => {
  loading.value = true
  try {
    currentPage.value = page
    const res = await getAndroidVersionList({
      page: page,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    })
    
    if (res.code === 200) {
      androidVersions.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取系统版本列表失败')
    }
  } catch (error) {
    console.error('获取系统版本列表失败:', error)
    ElMessage.error('获取系统版本列表失败')
  } finally {
    loading.value = false
  }
}

// 处理每页显示数量变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchAndroidVersions(1)
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  fetchAndroidVersions(page)
}

// 处理表格选择变化
const handleSelectionChange = (selection: AndroidVersion[]) => {
  selectedVersions.value = selection
}

// 删除单个系统版本
const deleteVersion = (row: AndroidVersion) => {
  ElMessageBox.confirm(`确定要删除系统版本 "${row.android_name}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      const res = await deleteAndroidVersion(row.id)
      
      if (res.code === 200) {
        ElMessage.success('系统版本已删除')
        fetchAndroidVersions(
          androidVersions.value.length === 1 && currentPage.value > 1 
            ? currentPage.value - 1 
            : currentPage.value
        )
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除系统版本出错:', error)
      ElMessage.error('删除失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 批量删除系统版本
const batchDeleteVersions = () => {
  if (selectedVersions.value.length === 0) {
    ElMessage.warning('请先选择要删除的系统版本')
    return
  }
  
  const versionNames = selectedVersions.value.map(v => v.android_name).join('、')
  const versionIds = selectedVersions.value.map(v => v.id)
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedVersions.value.length} 个系统版本吗？\n${versionNames}`, '批量删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      // 使用新的批量删除API
      const res = await batchDeleteAndroidVersions(versionIds)
      
      if (res.code === 200) {
        ElMessage.success(`成功删除 ${selectedVersions.value.length} 个系统版本`)
        fetchAndroidVersions(
          androidVersions.value.length === selectedVersions.value.length && currentPage.value > 1 
            ? currentPage.value - 1 
            : currentPage.value
        )
      } else {
        ElMessage.error(res.msg || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除系统版本出错:', error)
      ElMessage.error('批量删除失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 用户取消删除
  })
}
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  .header {
    padding-bottom: 15px;
    border-bottom: 1px solid var(--art-border-color);

    h3 {
      font-size: 18px;
      font-weight: 500;
    }
  }

  .filter-bar {
    margin: 20px 0;
    
    .action-buttons {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style> 